package com.java.second_goods.common.interceptor;

import com.java.second_goods.common.annotation.RequireAdmin;
import com.java.second_goods.common.exception.UnauthorizedException;
import com.java.second_goods.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * JWT认证拦截器
 *
 * @author clothing-rental
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        Method method = handlerMethod.getMethod();

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 检查方法是否需要管理员权限
        if (method.isAnnotationPresent(RequireAdmin.class) || handlerMethod.getBeanType().isAnnotationPresent(RequireAdmin.class)) {
            RequireAdmin requireAdmin = method.getAnnotation(RequireAdmin.class);
            if (requireAdmin == null) {
                requireAdmin = handlerMethod.getBeanType().getAnnotation(RequireAdmin.class);
            }

            if (requireAdmin.value()) {
                // 验证token
                if (token == null) {
                    throw new UnauthorizedException("Authorization token is required");
                }

                try {
                    // 验证是否为管理员
                    Boolean isAdmin = jwtUtil.isAdmin(token);
                    if (!isAdmin) {
                        throw new UnauthorizedException(requireAdmin.message());
                    }
                } catch (Exception e) {
                    throw new UnauthorizedException("Invalid or expired token");
                }
            }
        }

        // 如果有token，则设置用户信息到请求中，供后续使用
        if (token != null) {
            try {
                String username = jwtUtil.getUsernameFromToken(token);
                Integer userId = jwtUtil.getUserIdFromToken(token);
                Boolean isAdmin = jwtUtil.isAdmin(token);

                request.setAttribute("username", username);
                request.setAttribute("userId", userId);
                request.setAttribute("isAdmin", isAdmin);
            } catch (Exception e) {
                // Token解析失败，但不阻止请求继续，后续需要认证的功能会通过注解验证
            }
        }

        return true;
    }
}